from rest_framework import serializers

from order_app.models import OrderInfo


class OrderSerializer(serializers.ModelSerializer):
    username = serializers.CharField(read_only=True, source='user.username')

    class Meta:
        def check_status(value):
            """检查器"""
            if not (value >= 1 and value <= 5):
                raise serializers.ValidationError('1<=status<=5')

        fields = ['order_id', 'username', 'total_count', 'total_amount',
                  'freight',
                  'pay_method', 'status', 'create_time']
        model = OrderInfo
        extra_kwargs = {
            'user': {
                'required': False,
            },
            'status': {
                'validators': [check_status],
                'required': True,
            }
        }
